﻿using System;
using System.IO;
using System.Web.Hosting;
using System.Xml;
using System.Xml.Linq;
using Wayloop.Blog.Core.Extensions;


namespace Wayloop.Blog.Core.Services.Impl
{
    public class XmlConfigurationService : IConfigurationService
    {
        private string configurationFilePath;


        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        /// <value>The title.</value>
        public string Title { get; set; }


        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        /// <value>The description.</value>
        public string Description { get; set; }


        /// <summary>
        /// Gets or sets the author name.
        /// </summary>
        /// <value>The author name.</value>
        public string AuthorName { get; set; }


        /// <summary>
        /// Gets or sets the author email address.
        /// </summary>
        /// <value>The author email address.</value>
        public string AuthorEmailAddress { get; set; }


        /// <summary>
        /// Initializes a new instance of the <see cref="XmlConfigurationService"/> class.
        /// </summary>
        public XmlConfigurationService()
        {
            Initialize();
        }


        private void Initialize()
        {
            configurationFilePath = HostingEnvironment.MapPath("~/App_Data/configuration.xml");
            Refresh();
        }


        /// <summary>
        /// Refreshes this instance.
        /// </summary>
        public void Refresh()
        {
            using (var fileStream = File.OpenRead(configurationFilePath)) {
                using (var xmlReader = XmlReader.Create(fileStream)) {
                    XDocument xmlDocument = XDocument.Load(xmlReader);
                    if (xmlDocument.Root == null) {
                        throw new InvalidOperationException("Configuration data missing.");
                    }

                    XElement rootNode = xmlDocument.Root;
                    Title = rootNode.XPathSelectElementValue("title");
                    Description = rootNode.XPathSelectElementValue("description");
                    AuthorName = rootNode.XPathSelectElementValue("authorname");
                    AuthorEmailAddress = rootNode.XPathSelectElementValue("authoremailaddress");
                }
            }
        }
    }
}